#! /bin/bash
# AOSC apt-spy equiviant. Reads mirror list from http://www.anthonos.org/mirrors.list and performs speed tests.
# apt-spy.conf should be:
# # apt-spy.conf START
# Sources="os2 os2-anthonos" (Something like that)
# Method=[ ping | wget ] (Defines how to perform tests)
# MainURL=http://mirror.anthonos.org/mirrors.list
# # End of apt-spy.conf / DEFAULTCONF.
# -*- vim:fenc=utf-8:shiftwidth=2::softtabstop=2:autoindent

# Copyright (C) 2006-2012 Bart Martens <bartm@knars.be> # I copied die_hard() from update-flashplugin-nonfree...
# Copyright (C) 2014 Arthur Wang <arthur200126@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.	If not, see <http://www.gnu.org/licenses/>.



set -e

ap(){ printf '$q ' "$@"; }
vd(){ echo "$1=$(ap $2)"; }
return_0() { return 0; }
trap "return_0" 0

die_hard() {
	echo -e "ERROR: $1" >&2
	echo "More information might be available at:" >&2
	echo "	https://github.com/...../wiki" >&2
	exit 1
}

((EUID)) && die_hard "must be root (or hack the script)"

show_usage() {
	echo "Usage:"
	echo "	apt-spy --update"
	echo "	apt-spy --restore"
	echo "Additional options:"
	echo "	--verbose"
	echo "	--quiet"
	echo "	--ping"
	echo "	--wget"
	exit 1
}

testping() {
	pingregex='= [^/]*/([0-9]+\.[0-9]+)' # Regular Expression, see Wikipedia. （正则表达式）
	[[ $(ping -q -c 4 $1) =~ $pingregex ]] && printf "${BASH_REMATCH[1]:1}"|| printf "fail" # Wikipedia Bash: Regex.
}

testwget() {
	# Needs to be reviewed.
	# Using time may skip the 404 checking; but using sed seems to be complicated for me.
	# Of course I am happy to make everything something like a string of number giving the time taken.
	( TIMEFORMAT='%3R' time wget -nv -O /dev/null http://$1/path/to/test/file ) 2>&1 | grep real # | sed -e 's|^.*(\([0-9.]\+ [KM]B/s\)).*$|\1|' || printf "0"
}

sort_and_select() {
	j=0
	for i in $Mirrors; do
		((j++))
		Mirror_$j="$(test${Method} $i)"
		[ "Mirror_$j" == "fail"] && FAILEDMIRRORS="$i $FAILEDMIRRORS" || ( TESTEDMIRRORS="$i $TESTEDMIRRORS"; Time="$i $Time" ) 
	done
	for ((i=0;i<j;i++)); do
		 
	done
}

savesuccess() {
	for site in $TESTEDMIRRORS
	do
		printf "deb $site/ os2-repo "
		for repo in $Sources 
		do
			 printf "$repo" # Currently 
		done
		echo; echo
	done
}

commentfail() {
	for f_site in $FAILEDMIRRORS
	do
		for f_repo in $Sources
		do
			# Printf some comments here
		done
	done
}

Sources="os2 os2-anthonos"
Method=ping
MainURL=http://mirror.anthonos.org/mirrors.list

if [ -r /etc/apt/apt-spy.conf ]; then
	. /etc/apt/apt-spy.conf 
else
	echo -e "Sources=$Sources\nMethod=$Method\nMainURL=$MainURL" > /etc/apt-spy.conf
	echo "Config not found. Writing Defaults."
fi

getopt_temp=`getopt -o urpwvq --long update,backup,ping,wget,verbose,quiet -n 'apt-spy' -- "$@"` || show_usage
eval set -- "$getopt_temp" || show_usage

while true
do
	case "$1" in
		-u|--update)
			ACTION="update"
			shift
			;;
		-r|--restore)
			ACTION="restore"
			shift
			;;
		-p|--ping)
			Method=ping
			shift
			;;
		-w|--wget)
			Method=wget
			shift
			;;
		-v|--verbose)
			verbose=yes
			shift
			;;
		-q|--quiet)
			quiet=yes
			shift
			;;
		--)
			shift
			break
			;;
		*)
			echo "Internal error!"
			exit 1
			;;
		esac
done
[ "$ACTION" != "none" -a $# -eq 0 ] || show_usage
[ "$verbose" != "yes" ] || echo "options: $getopt_temp"


case "$ACTION" in
	update)
		mv /etc/apt/sources.list ~/sources.list.bak # Do a backup
		Mirrors="`wget -nv -O - http://mirror.anthonos.org/mirrors.list`" || ((echo "Trying to use local mirror list" && Mirrors="`cat /etc/apt/mirrors.list`") || die_hard "AOSC apt-spy can\'t get a mirror list.")
		sort_and_select	 
		echo -e	"# sources.list genereted by AOSC apt-spy.\n# See:\`$0 --help\` for more information." > /etc/apt/sources.list || die_hard "Cannot write to sources.list, please check permissions:\n`ls -alh /etc/apt`"
		savesuccess >> /etc/apt/sources.list
		commentfail >> /etc/apt/sources.list
		;;
	restore)
		mv ~/sources.list.bak /etc/apt/sources.list || die_hard "No backup files found. Make sure sources.list.bak is inside your \$HOME directory."
		;;
esac
